package tianrun.ziguan.api.calculate.config.service.influxdb.impl;

import org.influxdb.querybuilder.SelectQueryImpl;
import org.influxdb.querybuilder.WhereQueryImpl;
import org.influxdb.querybuilder.clauses.RawTextClause;
import org.influxdb.querybuilder.time.DurationLiteral;
import tianrun.ziguan.api.calculate.config.enums.QueryTypeEnum;
import tianrun.ziguan.api.calculate.config.service.influxdb.common.QueryBody;

import java.util.Collection;
import java.util.List;

import static org.influxdb.querybuilder.BuiltQuery.QueryBuilder.*;
import static tianrun.ziguan.api.calculate.config.config.influxdb.InfluxDbName.*;

public class BuildQuery {

    public static SelectQueryImpl query(String dbName,List<String> tables, String label, long start, long end) {
        //sum 和 avg 因为数据库的 value 值是String类型 influxDB数据库不支持String类型的值进行sum和avg函数的使用
        return select()
                .column(COLUMN)
                .from(dbName, tables.toArray(new String[]{}))
                .where(new RawTextClause(String.format(LABEL, label)))
                .and(lte(TIME, ti(end, DurationLiteral.MILLISECONDS)))
                .and(gte(TIME, ti(start, DurationLiteral.MILLISECONDS)))
                .tz(TIME_ZONE);
    }

    public static SelectQueryImpl query(String dbName, QueryBody body) {
        WhereQueryImpl<SelectQueryImpl> where = select(body.getScope().clause)
                .from(dbName, convertToString(body.getTableName()))
                .where(body.getLabelsCondition());

        if (body.getStartTime() != null) {
            where = where.and(gte(TIME, ti(body.getStartTime(), DurationLiteral.MILLISECONDS)));
        }

        if (body.getEndTime() != null) {
            where = where.and(lte(TIME, ti(body.getEndTime(), DurationLiteral.MILLISECONDS)));
        }

        SelectQueryImpl tz = where.tz(TIME_ZONE);

        if (QueryTypeEnum.all.equals(body.getScope())) {
            return tz;
        }
        return tz.groupBy(body.getGroupingBy());
    }

    private static String convertToString(Collection<String> strings){
        if (strings.isEmpty())return "";
        StringBuilder builder = new StringBuilder();
        strings.forEach(s -> builder.append("\"").append(s).append("\","));
        builder.deleteCharAt(builder.length()-1);
        return builder.toString();
    }
}
